package com.stone.mythread;

import java.util.concurrent.*;

/**
 * 创建线程的方式四：使用线程池
 */
public class ThreadPool implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.err.println(Thread.currentThread().getName() + " : " + i);
            }
        }
    }

    public static void main(String[] args) {
        // 1、提供指定线程数量的线程池
        ExecutorService service = Executors.newFixedThreadPool(10);
        ThreadPoolExecutor service1 = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);

        // 设置线程池的属性
        service1.setCorePoolSize(10);
        service1.setMaximumPoolSize(2);
        service1.setKeepAliveTime(100, TimeUnit.MINUTES);

        // 2、执行指定的线程的操作，需要提供实现 Runnable 接口或 Callable 接口实现类的对象
        service.execute(new ThreadPool()); // 适合使用 Runnable
        service.execute(new ThreadPool()); // 适合使用 Runnable

        // 3、关闭连接
        service.shutdown();
    }
}
